package com.example.articleservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.articleservice.entity.Article;
import com.example.articleservice.entity.ArticleCategory;
import com.example.articleservice.entity.Category;
import com.example.articleservice.entity.vo.ArticleVO;
import com.example.articleservice.service.*;
import com.example.common.Result;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author Mr.Tang
 * @since 2024-06-22
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Value("${page.pageSize:3}")
    private int pageSize;

    @Resource
    private IArticleService articleService;

    @Resource
    private IArticleCategoryService articleCategoryService;

    @Resource
    private ICategoryService categoryService;

    @Resource
    private IUserService userService;

    @Resource
    private ICommentService commentService;

    @Transactional
    @PostMapping("/add")
    public Result add(ArticleVO articleVO,
                      @RequestHeader(value = "uid", required = false) Long uid) {
        // 1. 参数校验
        if (articleVO == null || !StringUtils.hasLength(articleVO.getTitle())
                || !StringUtils.hasLength(articleVO.getContent())
                || articleVO.getCid() == null
                || articleVO.getCid() <= 0
                || uid == null
                || uid <= 0) {
            return Result.fail(-1, "非法参数");
        }
        articleVO.setUid(uid);

        // 2. 调用service
        boolean result = articleService.save(articleVO);
        if (result) {
            ArticleCategory articleCategory = new ArticleCategory();
            articleCategory.setAid(articleVO.getAid());
            articleCategory.setCid(articleVO.getCid());

            // 3. 文章和分类管理表中添加数据
            boolean finalResult = articleCategoryService.save(articleCategory);

            // 4. 将结果返回给前端
            return Result.success();
        }

        return Result.fail(-1, "添加失败");
    }


    @GetMapping("/getById")
    public Result getById(Long aid) {
        // 1. 参数校验
        if (aid == null || aid <= 0) {
            return Result.fail(-1, "非法参数");
        }

        // 2. 查询文章信息
        Article article = articleService.getById(aid);
        if (article == null || article.getAid() <= 0) {
            return Result.fail(-2, "没有找到该文章信息");
        }
        ArticleVO articleVO = new ArticleVO();
        articleVO.setAid(article.getAid());
        articleVO.setContent(article.getContent());
        articleVO.setTitle(article.getTitle());

        // 3. 查询文章对应的 cid(分类id)
        QueryWrapper<ArticleCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("aid", aid);
        ArticleCategory articleCategory = articleCategoryService.getOne(wrapper);
        if (articleCategory != null) {
            // 组装 cid
            articleVO.setCid(articleCategory.getCid());
            // 组装 category
            Category category = categoryService.getById(articleCategory.getCid());
            if (category != null && category.getCid() > 0) {
                articleVO.setCategory(category.getName());
            }

        }

        // 4. 组装作者信息
        String username = userService.getNameByUid(article.getUid());
        articleVO.setUsername(username);
        articleVO.setUid(article.getUid());

        // 4. 组装数据, 返回给前端
        return Result.success(articleVO);
    }


    @Transactional
    @PostMapping("/update")
    public Result update(ArticleVO articleVO,
                      @RequestHeader(value = "uid", required = false) Long uid) {
        // 1. 参数校验
        if (articleVO == null || !StringUtils.hasLength(articleVO.getTitle())
                || !StringUtils.hasLength(articleVO.getContent())
                || articleVO.getCid() == null
                || articleVO.getCid() <= 0
                || uid == null
                || uid <= 0
                || articleVO.getAid() == null
                || articleVO.getAid() <= 0) {
            return Result.fail(-1, "非法参数");
        }
        articleVO.setUid(uid);

        // 2. 调用service
        UpdateWrapper<Article> wrapper = new UpdateWrapper<>();
        wrapper.eq("uid", uid);
        wrapper.eq("aid", articleVO.getAid());
        boolean result = articleService.update(articleVO, wrapper);
        if (result) {
            // 3. 删除原来的关联数据
            QueryWrapper<ArticleCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("aid", articleVO.getAid());
            ArticleCategory articleCategory = articleCategoryService.getOne(queryWrapper);
            if (articleCategory != null && articleCategory.getAcid() > 0) {
                // 存在关联关系, 删除
                articleCategoryService.removeById(articleCategory.getAcid());
            }
            articleCategory.setAid(articleVO.getAid());
            articleCategory.setCid(articleVO.getCid());

            // 4. 文章和分类管理表中添加数据
           articleCategoryService.save(articleCategory);

            // 5 将结果返回给前端
            return Result.success();
        }
        return Result.fail(-1, "修改失败");
    }


    @GetMapping("/getUserArticle")
    public Result getUserArticleList(Long uid) {
        // 1. 校验参数
        if (uid == null || uid <= 0) {
            return Result.fail(-1, "非法参数");
        }
        // 2. 查询用户的所有文章
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", uid);
        wrapper.orderByDesc("aid");
        List<Article> list = articleService.list(wrapper);
        // 3. 返回
        return Result.success(list);
    }


    /**
     * 删除文章并且删除当前文章的所有评论信息
     * @param aid 文章id
     * @param uid 用户id(从header中获取)
     * @return
     */
    @GlobalTransactional  // 开启分布式事务
    @PostMapping("/delByAid")
    public Result deleteByAid(Long aid,
                              @RequestHeader(value = "uid", required = false) Long uid) {
        // 1. 参数校验
        if (aid == null || aid <= 0 || uid == null || uid <= 0) {
            return Result.fail(-1, "非法参数");
        }

        // 2. 构建删除条件
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("aid",aid);
        wrapper.eq("uid", uid);   // 文章归属权的判断,确认用户是作者
        // 删除当前文章
        boolean remove = articleService.remove(wrapper);
        if (!remove) {
            return Result.fail(-2, "服务发生错误");
        }
        // 删除当前文章下的所有评论信息
        commentService.delByAid(aid);

        // 3. 返回
        return Result.success();
    }


    @GetMapping("/getListByPage")
    public Result getListByPage(Integer pageIndex) {
        if (pageIndex == null || pageIndex <= 0) {
            // 参数的校正
            pageIndex = 1;
        }
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("aid");
        Page<Article> page = new Page<>(pageIndex, pageSize);
        Page<Article> list = articleService.page(page, wrapper);
        // 返回
        return Result.success(list);
    }

    @RequestMapping("/getUidByAid")
    public Long getUidByAid(Long aid) {
        if (aid == null || aid <= 0) {
            return 0L;
        }
        Article article = articleService.getById(aid);
        if (article == null) {
            return 0L;
        }
        return article.getUid();
    }

}
